package com.jeesite.modules.scheduler;

import com.jeesite.common.config.Global;
import com.jeesite.modules.dp.entity.kccode.DpKechengcode;
import com.jeesite.modules.dp.service.kccode.DpKechengcodeService;
import com.jeesite.modules.dp.service.order.DpOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class KcCodeUnLockScheduler {

    @Autowired
    private DpKechengcodeService dpKechengcodeService;

    private final Logger log = LoggerFactory.getLogger(KcCodeUnLockScheduler.class);

    /**
     * 判断是否已过期
     *
     * @param lockTime 被锁定时间
     * @return 过期：true
     */
    private boolean expired(Date lockTime) {
        int expireSeconds = Integer.parseInt(Global.getConfig("wxpay.expire.seconds", "300"));
        long nowMills = System.currentTimeMillis();
        long lockMills = lockTime.getTime();
        long diffSeconds = (nowMills - lockMills) / 1000;
        return diffSeconds > expireSeconds;
    }

    /**
     * 定时查找被锁定的课程编码，如果锁定时间已过期，则释放该课程码
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void execute() {
        try {
            List<DpKechengcode> list = dpKechengcodeService.findLockedKcCodes();
            if (list == null || list.isEmpty()) {
                return;
            }
            for (DpKechengcode data : list) {
                if (data.getLocktime() == null || !expired(data.getLocktime())) {
                    continue;
                }
                //解锁
                dpKechengcodeService.unLockKcCode(data.getId());
                log.info("释放课程编码锁，课程码: {}, 原锁定用户名: {}, 原锁定订单号: {}", data.getKccode(), data.getUno(), data.getLockorderid());
            }
        } catch (Exception e) {
            log.error("释放课程码锁失败, errMsg: {}", e.getMessage(), e);
        }

    }
}
